package com.wheel.autoconfigure.shiro.matcher;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.util.DigestUtils;

/**
 * <dt>Description:DefaultCredentialsMatcher</dt>
 * <dd>默认密码加密方法</dd>
 *
 * @author wnfbx@163.com
 * @version 1.0 <i>2019年6月6日 下午4:23:12</i>
 * @since jdk1.7+
 */
public class DefaultCredentialsMatcher extends SimpleCredentialsMatcher {

    private static final String PASSWORD_ENCODE_KEY = "%s:%s:peacock:[~@!*&_$#@!)~]";

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        Object accountCredentials = getCredentials(info);
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        // 使用重置密码加密方法
        String tokenCredentials = encodePassword(usernamePasswordToken.getUsername(), String.valueOf(usernamePasswordToken.getPassword()));
        return equals(tokenCredentials, accountCredentials);
    }

    public static String encodePassword(String username, String password) {
        return DigestUtils.md5DigestAsHex(String.format(PASSWORD_ENCODE_KEY, username, password).getBytes());
    }
}